package com.hxitsys.common.core.domain;

import com.hxitsys.common.constant.HttpStatus;
import org.springframework.util.Assert;

import java.util.HashMap;

/**
 * the 响应结果 for REST response
 * @author kangtengjiao
 * @date 2022-03-14
 * @usage Success: return R.success().msg(msg);
 *                 return R.success(data).msg(msg);
 *                 return R.success(Data.getInstance().put("key","value")...).msg(msg);
 *        Fail   : return R.fail().msg(msg) or R.fail(code).msg(msg)
 */
public class R<T> {
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 提示信息
     */
    private String msg;
    /**
     * 查询到的结果数据
     */
    private T data;

    // Begin getters & setters
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    // End getters & setters

    // Begin 主调方法

    // success 专用
    private R(){this.code = HttpStatus.SUCCESS;}
    private R(T data) {this();this.data = data;}
    public static R<Void> success() { return new R<>();}
    public static <T> R<T> success(T data) { return new R<>(data); }

    // fail 专用
    private R(Integer code) {
        Assert.isTrue(code != null, "内部程序错误");
        this.code = code;
    }
    public static R<Void> fail() {
        return new R<>(HttpStatus.ERROR);
    }
    public static R<Void> fail(String msg) {
        return fail().msg(msg);
    }
    public static R<Void> fail(Integer code) {
        R<Void> f = new R<>(code);
        Assert.isTrue(HttpStatus.SUCCESS != code, "error");
        return f;
    }

    // success 与 fail 共用
    public R<T> msg(String msg) {this.setMsg(msg);return this;}

    // End 主调方法

    // Begin 动态dataMap
    public static class Data extends HashMap<String, Object> {
        private Data(){}
        public static Data getInstance(){return new Data();}
        public Data put(String key, Object value) {super.put(key, value);return this;}
    }
    // End 动态dataMap

}
